package com.ncloud.resman.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.body.Result;
import com.ncloud.common.exception.UserException;
import com.ncloud.common.utils.ResultUtil;
import com.ncloud.resman.busi.VirtualMachineBusi;
import com.ncloud.resman.constant.ResConstant;
import com.ncloud.resman.entity.VirtualMachine;
import com.ncloud.resman.service.VirtualDiskService;
import com.ncloud.resman.service.VirtualMachineService;
import com.ncloud.resman.service.VirtualNetworkCardService;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


/**
 * Created by shiqiang on 2017/8/15.
 */
@Api(value = "自动化运维设备管理", description = "虚拟机管理", tags = "虚拟机管理",
        basePath="/",consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/resman/virtual")
public class VirtualMachineController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private VirtualMachineBusi virtualMachineBusi;
    @Autowired
    private VirtualMachineService virtualMachineService;
    @Autowired
    private VirtualDiskService virtualDiskService;
    @Autowired
    private VirtualNetworkCardService virtualNetworkCardService;
    /*机房机柜设备树*/
    @GetMapping(value = "/roomTree")
    public Result<JSONObject> getRoomTree( HttpServletRequest request){
        return ResultUtil.success(virtualMachineBusi.getRoomTreeInfo());
    }
    /*新增虚拟机*/
    @PostMapping(value = "/virtualMachine")
    public Result<Object> saveVirtualMachine(HttpServletRequest request, @RequestBody VirtualMachine virtualMachine) throws Exception {
        logger.info("虚拟机新增报文信息："+ JSON.toJSONString(virtualMachine));
        JSONObject json = new JSONObject();
        Object userID = request.getAttribute("userID");
        if(StringUtils.isEmpty(userID)){
            throw new UserException(2001,"用户ID不存在！");
        }else{
            json.put("userID",Long.parseLong(userID.toString()));
        }
        virtualMachineBusi.addVirtualMachine(virtualMachine,json);
        return ResultUtil.success();
    }
    /*虚拟机信息修改*/
    @PutMapping(value = "/virtualMachine")
    public Result<Object> modifyLocationDevice(@RequestBody VirtualMachine virtualMachine,
                                           HttpServletRequest request) throws Exception {
        logger.info("虚拟机修改报文信息："+ JSON.toJSONString(virtualMachine));
        JSONObject json = new JSONObject();
        Object userID = request.getAttribute("userID");
        if(StringUtils.isEmpty(userID)){
            throw new UserException(2001,"用户ID不存在！");
        }else{
            json.put("userID",Long.parseLong(userID.toString()));
        }
        virtualMachineBusi.updateVirtualMachine(virtualMachine,json);
        return ResultUtil.success();
    }

    /*虚拟硬盘删除*/
    @DeleteMapping(value = "/disk/{diskId}")
    public Result deleteVirtualDisk(@PathVariable("diskId") Long diskId){
        virtualDiskService.deleteVirtualDisk(diskId);
        return ResultUtil.success();
    }

    /*虚拟硬盘删除*/
    @DeleteMapping(value = "/networkCard/{cardId}")
    public Result deleteNetworkCard(@PathVariable("cardId") Long cardId){
        virtualNetworkCardService.deleteVirtualNetworkCard(cardId);
        return ResultUtil.success();
    }

    /*删除虚拟机*/
    @DeleteMapping(value = "/virtualMachine/{virtualId}")
    public Result deleteVirtualMachine(@PathVariable("virtualId") Long virtualId){
        virtualMachineBusi.deleteVirtualMachine(virtualId);
        return ResultUtil.success();
    }

    /*cpu核数校验*/
    @GetMapping(value = "/server/validate/cpu/{deviceId}/{num}")
    public Result<?> getCpuState( @PathVariable("deviceId") Long deviceId,@PathVariable("num") Long num){
        boolean flag = false;
        Long unUsed = virtualMachineBusi.computeSurplusSpace(deviceId, ResConstant.UNIT_TYPE_CPU);
        if(num <= unUsed){
            flag = true;
        }
        return ResultUtil.success(flag);
    }

    /*内存数校验*/
    @GetMapping(value = "/server/validate/memory/{deviceId}/{num}")
    public Result<?> getMemoryState( @PathVariable("deviceId") Long deviceId,@PathVariable("num") Long num){
        boolean flag = false;
        Long unUsed = virtualMachineBusi.computeSurplusSpace(deviceId, ResConstant.UNIT_TYPE_RAM);
        if(num <= unUsed){
            flag = true;
        }
        return ResultUtil.success(flag);
    }

    /*硬盘大小校验*/
    @GetMapping(value = "/server/validate/disk/{hostIp}/{num}")
    public Result<?> getMemoryState( @PathVariable("hostIp") String hostIp,@PathVariable("num") Long num){
        boolean flag = false;
        Long unUsed = virtualMachineBusi.getDiskCapacity(hostIp);
        if(num <= unUsed){
            flag = true;
        }
        return ResultUtil.success(flag);
    }
    /*修改虚拟机状态*/
    @GetMapping(value = "/virtualMachine/state/{virtualId}/{state}")
    public Result<?> updateVirtualMachineState(@PathVariable("virtualId") Long virtualId, @PathVariable("state") String state){
        virtualMachineService.updateVirtualMachineState(virtualId,state);
        return ResultUtil.success();
    }
    /*获取主机服务器资源信息*/
    @GetMapping(value = "/server/info/{deviceId}")
    public Result<?> getServerInfos(@PathVariable("deviceId") Long deviceId){
        JSONObject obj = virtualMachineBusi.getServerInfo(deviceId);
        logger.info("服务器资源综合信息："+obj.toJSONString());
        return ResultUtil.success(obj);
    }

    /*获取虚拟机资源信息*/
    @GetMapping(value = "/virtualMachine/info/{virtualId}")
    public Result<JSONObject> getVirtualMachineInfo(@PathVariable("virtualId") Long virtualId){
        JSONObject obj = virtualMachineBusi.getVirtualMachineInfo(virtualId);
        logger.info("虚拟机资源综合信息："+obj.toJSONString());
        return ResultUtil.success(obj);
    }
}
